package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RocketMQMessageListener(
        consumerGroup = MQConstants.SECKILL_ORDER_DELAY_GROUP,
        topic = MQConstants.SECKILL_ORDER,
        selectorExpression = MQConstants.SECKILL_CREATE_DELAY_TAG
)
public class OrderSuccessDelayMQListener implements RocketMQListener<Map> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Map map) {
        System.out.println("进入到延时队列中");
        Object orderNo = map.get("data");
        Object seckillId = map.get("seckillId");
        Long goodId = null;
        if (seckillId instanceof Long) {
            goodId = (Long) seckillId;
        } else if (seckillId instanceof Integer) {
            goodId = ((Integer) seckillId).longValue();
        }
        //修改订单的状态为超时未支付，修改时后加一个where status = 0，如果修改成功说明未支付，如果没修改成功说明支付了
        int count = orderInfoService.changStatus(orderNo+"", OrderInfo.STATUS_TIMEOUT);
        if (count > 0) {
            //回补真实库存
            seckillGoodService.incrCount(goodId);
            //回补预库存，把真实的库存放到redis
            seckillGoodService.syncPreStockCount(goodId);
            //发送广播消息修改本地表示
            rocketMQTemplate.syncSend(MQConstants.SECKILL_CREATE_BROAD_DEST, seckillId);
        }
    }
}
